package com.book.bookmanager.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.book.bookmanager.pojo.User;
import com.book.bookmanager.service.userService;
import com.book.common.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(tags = "登录注册管理")
public class userController {
    /**
     * controller层调用service层，创建service对象
     */
    @Autowired
    private userService us;
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 登录
     */

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/user/login")
    @ApiOperation("登录管理")
    public Result<Map<String, Object>> loginSuccess(@RequestBody User user) {
        Map<String, Object> data = us.login(user);
        if (data != null) {
            return Result.success(data);

        }
        return Result.fail(20002, "用户名或者密码错误");
    }
//	public String loginSuccess(Model model, User user, HttpSession session) {
//		/**
//		 * 查询用户是否存在
//		 */
//		try {
//			User user1 = us.queryByUser(user.getUser());
//			System.out.println(user1);
//			if (user1 != null) {
//				if (user1.getPassword().equals(user.getPassword())) {
//					String user2 = user1.getUser();
//					System.out.println(user1.toString());
//					session.setAttribute("user", user2);
//					return "redirect:/book/queryAll";
//				} else {
//					model.addAttribute("data", "密码不正确");
//					return "login";
//				}
//
//			} else {
//				/**
//				 * 用户不存在跳转登录
//				 */
//				model.addAttribute("data", "该用户不存在，请先注册");
//				return "login";
//			}
//
//		} catch (Exception e) {
//			e.printStackTrace();
//			return e.getMessage();
//		}
//	}


    /**
     * 注册
     */
    @RequestMapping("/toRegister")
    public String toRegister() {
        return "register";
    }

    @RequestMapping("/registerSuccess")
    @ApiOperation("注册管理")
    public Result<Map<String, Object>> toRegisterSuccess(@RequestBody User user) {
        /**
         * 添加信息到数据库
         */
        Map<String, Object> data = us.register(user);
        if (data != null) {
            return Result.success(data);

        }
        return Result.fail(20002, "用户名错误");
    }

    @GetMapping("/user/info")
    @ApiOperation("获取用户信息")
    public Result<Map<String, Object>> getUseInfo(@RequestParam("token") String token) {
        //根据token获取信息
        Map<String, Object> data = us.getUserInfo(token);
        if (data != null) {
            return Result.success(data);
        }
        return Result.fail(20003, "用户信息获取失败，请重新登录");
    }

    @PostMapping("/user/logout")
    @ApiOperation("注销")
    public Result<?> loginOut(@RequestHeader("X-Token") String token) {
        us.loginOut(token);
        return Result.success("注销成功");

    }

    @GetMapping("/menu_list")
    @ApiOperation("获取菜单")
    public Result<Map<String, Object>> getMenuList() {
        return Result.fail(20003, "获取列表失败，请刷新");
    }

    @GetMapping("/user/list")
    @ApiOperation("获取列表")
    public Result<Map<String, Object>> getUserList(@RequestParam(value = "userName", required = false) String userName,
                                                   @RequestParam(value = "pageNo") Long pageNo,
                                                   @RequestParam(value = "pageSize") Long pageSize) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(userName), User::getUserName, userName);

        Page<User> page = new Page<>(pageNo, pageSize);
        us.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());

        return Result.success(data);
    }

    @PostMapping("/addUser")
    public Result<?> addUser(@RequestBody User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        us.addUser(user);
        return Result.success("新增用户成功");
    }

    @PutMapping("/updateUser")
    public Result<?> updateUser(@RequestBody User user) {

        user.setIs_deleted(0);
        us.updateUserById(user);

        return Result.success("修改用户成功");
    }

    @GetMapping("/getUserByName/{name}")
    public Result<?> queryByName(@PathVariable("name") String name) {
        User user = us.queryByUser(name);
        if (user!=null){
        return Result.success(user);
        }
        return Result.fail("获取用户失败，用户不存在");
    }
    @DeleteMapping ("/deleteByName/{userName}")
    public Result<?> deleteById(@PathVariable("userName") String name) {
        us.removeByUser(name);
        return Result.success("删除成功");
    }
}
